﻿using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;
using MVCms.Core.Entities;


namespace MVCms.Web
{
    /// <summary>
    /// Html helper class for our module containers
    /// </summary>
    public static class Container
    {
        /// <summary>
        /// Html helper method for our module containers
        /// </summary>
        public static ModuleContainerHelper ModuleContainer(this HtmlHelper content, PageModule pluginModule)
        {
            return new ModuleContainerHelper(content, pluginModule);
        }
    }

    /// <summary>
    /// our container... using idisposable
    /// </summary>
    public class ModuleContainerHelper : IDisposable
    {
        /// <summary>
        /// the content that needs to be wrapped
        /// </summary>
        private readonly HtmlHelper _content;

        /// <summary>
        /// trick idisposable to act as a nice wrapper
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="pluginModule">The plugin module.</param>
        public ModuleContainerHelper(HtmlHelper content, PageModule pluginModule)
        {
            _content = content;

            //get our current themes' folder
            string theme = string.IsNullOrEmpty(HttpContext.Current.Session["Theme"].ToString())
                               ? "Default"
                               : HttpContext.Current.Session["Theme"].ToString();

            //read our container html
            var container = File.ReadAllText(HttpContext.Current.Request.MapPath("~/Content/" + theme + "/Containers/Default.htm"));

            //replace placeholders with actual values
            var result = container
                .Replace("[Title]", pluginModule.Title)
                .Replace("[ModuleManager]", "<span id=rem_" + string.Format("{0}_{1}_{2}", pluginModule.Position, pluginModule.Module.Controller, pluginModule.Module.Action) + ">X</span>")
                .Replace("[Content]",string.Format("{0}_{1}_{2}", pluginModule.Position, pluginModule.Module.Controller,pluginModule.Module.Action));

            _content.ViewContext.Writer.Write(result);
        }


        /// <summary>
        /// close our wrapper
        /// </summary>
        public void Dispose()
        {
            var end = string.Empty;
            _content.ViewContext.Writer.Write(end);
        }
    }
}